<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <!-- 级联选择框 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="catelist"
            :props="cateProps"
            expand-trigger="hover"
            @change="handleCatChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <!-- 动态属性表格 -->
          <el-table :data="manyParamsDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环遍历tag标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClosed(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加标签或者input -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editTableData(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deletedTableData"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyParamsDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环遍历tag标签 -->
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable>{{item}}</el-tag>
                <!-- 添加标签或者input -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editTableData(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deletedTableData"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDateColsed"
    >
      <!-- 添加表单 -->
      <el-form
        :model="addDateForm"
        :rules="addDateFormRules"
        ref="addDateFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addDateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDateColsed"
    >
      <!-- 修改表单 -->
      <el-form
        :model="editDateForm"
        :rules="editDateFormRules"
        ref="editDateFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editDateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表数据
      catelist: [],
      // 指定级联选择器的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //   存储选中的父级id值的数组
      selectedCateKeys: [],
      //   标签页默认选中的值
      activeTabName: "many",
      //   动态属性数据
      manyParamsDate: [],
      // 静态属性数据
      onlyParamsDate: [],
      //   添加对话框的显示与隐藏
      addDialogVisible: false,
      //   添加表单的数据
      addDateForm: {
        attr_name: ""
      },
      // 添加表单的验证规则
      addDateFormRules: {
        attr_name: [{ required: true, message: "不能为空", trigger: "blur" }]
      },
      //   修改按钮的对话框的显示与隐藏
      editDialogVisible: false,
      // 修改对话框的数据
      editDateForm: {
        attr_name: ""
      },
      // 修改对话框是验证规则
      editDateFormRules: {
        attr_name: [{ required: true, message: "不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //   获取商品分类数据
    async getCateList() {
      const { data } = await this.$http.get("categories");
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg);
      }
      this.catelist = data.data;
    },
    // 级联选择器状态改变时触发的函数
    async handleCatChange() {
      this.getParamsDate();
    },
    // 标签页被选中时触发 返回被选中的标签
    handleTabClick() {
      this.getParamsDate();
    },
    // 获取参数列表的数据请求函数
    async getParamsDate() {
      const { data } = await this.$http.get(
        `categories/${this.cataId}/attributes`,
        {
          params: { sel: this.activeTabName }
        }
      );
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg);
      }
      //   将字符串转化为数组的每一项
      //   不能直接判断并赋值 因为会造成没有内容 还是会出现tag标签
      data.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        //   判断input的显示与隐藏
        item.inputVisible = false;
        //   input输入的值
        item.inputValue = "";
      });
      //   console.log(item.attr_vals);

      //   判断数据是动态参数还是静态属性
      if (this.activeTabName === "many") {
        this.manyParamsDate = data.data;
      } else {
        this.onlyParamsDate = data.data;
      }
      console.log(data.data);
    },
    // 关闭添加对话框
    addDateColsed() {
      this.$refs.addDateFormRef.resetFields();
    },
    // 点击按钮，添加参数
    addDate() {
      this.$refs.addDateFormRef.validate(async valid => {
        if (!valid) {
          return this.message.error(data.meta.msg);
        }
        const { data } = await this.$http.post(
          `categories/${this.cataId}/attributes`,
          {
            attr_name: this.addDateForm.attr_name,
            attr_sel: this.activeTabName
          }
        );

        if (data.meta.status !== 201) return;
        this.$message.success(data.meta.msg);
        this.addDialogVisible = false;
        this.getParamsDate();
      });
    },
    // 关闭修改对话框进行重置操作
    editDateColsed() {
      this.$refs.editDateFormRef.resetFields();
    },
    // 点击确定按钮 发送请求 修改成功
    editDate() {
      this.$refs.editDateFormRef.validate(async valid => {
        if (!valid) return;
        const { data } = await this.$http.put(
          `categories/${this.cataId}/attributes/${this.editDateForm.attr_id}`,
          {
            attr_name: this.editDateForm.attr_name,
            attr_sel: this.activeTabName
          }
        );
        if (data.meta.status !== 200) return;
        this.$message.success(data.meta.msg);
        this.getParamsDate();
        this.editDialogVisible = false;
      });
    },
    // 点击按钮 显示修改对话框
    async editTableData(attrId) {
      this.editDialogVisible = true;
      //调用接口获取数据
      const { data } = await this.$http.get(
        `categories/${this.cataId}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeTabName }
        }
      );
      if (data.meta.status !== 200) return;
      this.editDateForm = data.data;
    },
    // 点击删除按钮，删除分类
    async deletedTableData() {
      const confirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirm !== "confirm") return this.$message.error("已取消删除");
      const { data } = await this.$http.delete(
        `categories/${this.cataId}/attributes/${this.editDateForm.attr_id}`
      );
      this.getParamsDate();
      this.$message.success(data.meta.msg);
    },
    // 鼠标按下或者离开焦点 触发处理函数
    async handleInputConfirm(row) {
      //   如果输入框中的值为空的时候 清空value值
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //   如果没有return，则证明输入的内容，需要做后续处理
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row)
    },
    // 点击按钮 切换tag为input输入框
    showInput(row) {
      row.inputVisible = true;
      //   在下次dom更新循环结束之后，执行延迟回调。在修改数据之后立即使用这个方法，获得更新后的dom
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除tag标签
    async handleClosed(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      const { data } = await this.$http.put(
        `categories/${this.cataId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(",")
        }
      );
      console.log(data);
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg);
      }
      this.$message.success(data.meta.msg);
    }
  },
  //   计算属性
  computed: {
    isBtnDisabled() {
      // 如果存储级联选择框选中的数组长度不等于三 就返回true禁用
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 选中的三级分类的id
    cataId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    // 标题名称
    titleText() {
      if (this.activeTabName === "many") {
        return "动态参数";
      }
      return "静态属性";
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 20px 0;
}
.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 100px;
}
</style>